import { OrganLogin, fakeMobileLogin } from '../services/api';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    uid: undefined,
    username: undefined,
    token: undefined,
  },

  effects: {
    *accountSubmit({ payload }, { call, put }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(OrganLogin, payload);
      yield put({
        type: 'loginHandle',
        payload: response,
      });
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
    },
    *mobileSubmit(_, { call, put }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(fakeMobileLogin);
      yield put({
        type: 'loginHandle',
        payload: response,
      });
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
    },
  },

  reducers: {

    loginHandle(state, { payload }) {
      if (payload.err) {
        return {
          ...state,
          status: 'error',
          type: 'account',
        };
      }
      return {
        ...state,
        uid: payload && payload.user_id,
        uname: payload && payload.user_name,
        token: payload && payload.access_token,
        status: 'ok',
        type: 'account',
      };
    },

    changeSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },

    logout(state) {
      return {
        ...state,
        status: 'logout',
        uid: undefined,
        token: undefined,
        uname: undefined,
      };
    },
  },
};

